import Axios from 'axios'
import {ElMessage} from 'element-plus'


// if (process.env.NODE_ENV === 'development') {
//   Axios.defaults.baseURL = 'http://localhost:8081'
// } else if (process.env === 'production') {
//   Axios.defaults.baseURL = 'https://netease2.bluej.cn/';
// }

Axios.defaults.timeout = 10000;
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

Axios.interceptors.request.use(config => {
  // let info = getToken();
  // if (!Util.isNullOrBlank(info)) {
  //   info = JSON.parse(info);
  //   let header = {version: 1.0, source: 'Web', token: info.token, uid: info.uid};
  //   config.headers['X-Auth-Token'] = JSON.stringify(header)
  // }
  return config
}, err => {
  ElMessage.error({message: '请求错误!'});
  return Promise.reject(err)
});

Axios.interceptors.response.use(response => {
  const data = response.data;
  console.log(data)
  if (Number(data.code) === 0) {
    return {data: data}
  } else if (Number(data.code) === 403) {
    ElMessage.error(data.message || "认证失败，请重新登陆");
    location.reload();// 为了重新实例化vue-router对象 避免bug
  } else {
    ElMessage.error("未知错误!");
    // return Promise.reject(null)
    return {err: data}
  }
}, error => {
  ElMessage.error({message: '请求错误!'});
  // return Promise.reject(error)
  return {err: error}
});

export function Get(url, params) {
  return new Promise((resolve, reject) => {
    Axios.get(url, params).then(res => {
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })
}

export function Post(url, params) {
  return new Promise((resolve, reject) => {
    Axios.post(url, params).then(res => {
      resolve(res);
    }).catch(err => {
      reject(err)
    })
  })
}
